package com.digital.herbarium.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import com.digital.herbarium.Entity.Specimen;
import com.digital.herbarium.Entity.SpecimenUrl;
import com.digital.herbarium.Entity.Stat;
import com.digital.herbarium.Exception.CustomException;
import com.digital.herbarium.Mapper.SpecimenMapper;
import com.digital.herbarium.Util.ExcelUtilHandler;
import com.digital.herbarium.Util.SpecimenUtil;
import com.digital.herbarium.Util.TimeUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class SpecimenService {

    @Autowired
    private SpecimenMapper specimenMapper;


    public PageInfo<Specimen>  getSpecimenInfo(Specimen specimen, int pageSize, int pageNum){
       // return specimenMapper.getSpecimenInfo(specimen);
        PageHelper.startPage(pageNum, pageSize);
        String lcode = specimen.getLibraryCode();
        if(!StrUtil.hasEmpty(lcode) && !StrUtil.hasBlank(lcode)){
            if(lcode.startsWith("WH")){
                String[] nlcode = lcode.split("WH");
                specimen.setBarCode(nlcode[1]);
            }else if (lcode.startsWith("HBDC")){
                String[] nlcode = lcode.split("HBDC");
                specimen.setBarCode(nlcode[1]);
            }else{
                specimen.setBarCode(lcode);
            }


            specimen.setLibraryCode(null);

        }
        List<Specimen> lists = specimenMapper.getSpecimenInfo(specimen);
        PageInfo<Specimen> pageInfo = new PageInfo<Specimen>(lists);
        return pageInfo;
    }

    public List<Specimen> getSpecimenInfo(Specimen specimen){
        List<Specimen> lists = specimenMapper.getSpecimenInfo(specimen);
        return lists;
    }

    public Integer addSpecimen(Specimen specimen){
        SpecimenUtil.checkInfo(specimen);
        //验证条形码是否存在
        Specimen s1 = new Specimen();
        s1.setBarCode(specimen.getBarCode());
        List<Specimen> slist = specimenMapper.getSpecimenInfo(s1);
        if(slist.size() > 0){
            throw  new CustomException(400,"该条形码已存在");
        }
        specimen.setState(1);
        specimen.setCreatetime(TimeUtil.getNow());
        specimenMapper.addSpecimen(specimen);
        return  specimen.getId();
    }

    //添加图片

    public void  addPic(MultipartFile file, HttpServletRequest request,Integer sid,String uploadPath){
        if (file.isEmpty()){
           // System.out.println("文件为空");
            throw  new CustomException(400,"文件为空");

        }

//        if(sid == 0){
//            throw  new CustomException(400,"id为空");
//        }

       // String staticPath = ClassUtils.getDefaultClassLoader().getResource("").getPath().replaceFirst("/","");
      //  String staticPath = ResourceUtils.getURL("classpath:").geta
        String contentType = file.getContentType();
        //String fileType = contentType.substring(0,contentType.lastIndexOf("/"));
        //String staticPath  = System.getProperty("user.dir");
        ;
//        String uploadPath = addressurl + File.separator + "upload/img";
//        System.out.println("上传路径"+uploadPath);

        //文件名
        String fileName = file.getOriginalFilename();
        //后缀名
        //  String suffixName = fileName.substring(fileName.lastIndexOf("."));
        File file1 = new File(uploadPath);
        if (!file1.exists()){
            file1.mkdir();
        }
        if (fileName!=null&&!"".equals(fileName.trim())){
            //String newName = UUID.randomUUID().toString().replace("-", "") + suffixName;

            //创建文件
            File desFile = new File(uploadPath + File.separator + fileName);
            //System.out.println("绝对路径：" + uploadPath);
            //将源文件写入服务器
            try {
                file.transferTo(desFile);
            } catch (IOException e) {
                e.printStackTrace();
            }



            try{

                String fileUrl = File.separator+"image" +File.separator+ fileName;
                String[] fns = fileName.split("\\.");
                SpecimenUrl su = new SpecimenUrl();
                su.setSid(sid);
                su.setImgUrl(fileUrl);
                su.setPicname(fns[0]);
                specimenMapper.addImg(su);

            }catch (Exception e){
                System.out.println("error:"+e);
            }

//            return Result.OK().data("fileUrl",fileUrl);
        }
    }



    //解析excel
    public void  addExcel(MultipartFile file, HttpServletRequest request,String uploadPath){
        ExcelReader reader = ExcelUtilHandler.getExcelReader(file, request, uploadPath);
        reader.addHeaderAlias("馆代码","libraryCode");
        reader.addHeaderAlias("条形码","barCode");
        reader.addHeaderAlias("模式类型","patternType");
        reader.addHeaderAlias("库存","inventory");
        reader.addHeaderAlias("标本状态","specimenStatus");
        reader.addHeaderAlias("采集人","gatherer");
        reader.addHeaderAlias("采集号","gatherNumber");
        reader.addHeaderAlias("采集日期","gatherDate");
        reader.addHeaderAlias("国家","country");
        reader.addHeaderAlias("省市","province");
        reader.addHeaderAlias("区县","district");
        reader.addHeaderAlias("海拔","altitude");
        reader.addHeaderAlias("负海拔","negativeAltitude");
        reader.addHeaderAlias("科","specimenFamily");
        reader.addHeaderAlias("属","specimenGenus");
        reader.addHeaderAlias("种","specimenSpecies");
        reader.addHeaderAlias("定名人","nominator");
        reader.addHeaderAlias("种下等级","plantingGrade");
        reader.addHeaderAlias("中文名","specimenName");
        reader.addHeaderAlias("鉴定人","authenticateEr");
        reader.addHeaderAlias("鉴定日期","authenticateDate");
        reader.addHeaderAlias("备注","remarks");
        reader.addHeaderAlias("地名","placeName");
        reader.addHeaderAlias("生境","habitat");
        reader.addHeaderAlias("经度","lon");
        reader.addHeaderAlias("纬度","lat");
        reader.addHeaderAlias("备注2","remark2");
        reader.addHeaderAlias("录入员","entryClerk");
        reader.addHeaderAlias("录入日期","entryDate");
        reader.addHeaderAlias("习性","habit");
        reader.addHeaderAlias("体高","bodyHeight");
        reader.addHeaderAlias("胸径","dbh");
        reader.addHeaderAlias("茎","stems");
        reader.addHeaderAlias("叶","leaf");
        reader.addHeaderAlias("花","flowers");
        reader.addHeaderAlias("果实","fruit");
        reader.addHeaderAlias("寄主","host");

        List<Specimen> specimens = reader.readAll(Specimen.class);
        //添加
        List<Specimen> specimens1 = new ArrayList<>();
        List<Specimen> theRest = specimenMapper.getTheRest();
        for (int i = 0; i < specimens.size(); i++) {
            boolean f = getTheRest(theRest, specimens.get(i).getBarCode());
            if(!f){
                specimens.get(i).setCreatetime(TimeUtil.getNow());
                specimens1.add(specimens.get(i));
            }

        }
        specimenMapper.bachAdd(specimens1);

    }
    public  boolean getTheRest(List<Specimen>theRest, String value){
        for (int i = 0; i < theRest.size(); i++) {
            if(theRest.get(i).getBarCode() != null && theRest.get(i).getBarCode().equals(value)){
                return true;
            }

        }
        return false;
    }

    public  void editSpecimen(Specimen specimen){
        if(specimen.getId() == null || specimen.getId() == 0){
            throw  new CustomException(400,"缺少信息id");
        }
        SpecimenUtil.checkInfo(specimen);
        //验证条形码是否存在
        Specimen s1 = new Specimen();
        s1.setBarCode(specimen.getBarCode());
        s1.setId(specimen.getId());
        Integer sl1 = specimenMapper.checkExist(s1);
        if(sl1 > 0){
            throw  new CustomException(400,"该条形码已存在");
        }
        specimenMapper.editSpecimen(specimen);
    }

    public void delSpecimen(String id){
        if(StrUtil.hasEmpty(id) || StrUtil.hasBlank(id)){
            throw  new CustomException(400,"缺少信息id");
        }
        String[] strArr = id.split(",");
        Long[] ids = Convert.toLongArray(strArr);
        specimenMapper.delSpecimen(ids);
    }

    public PageInfo<SpecimenUrl> getNoWaterImage(){
        PageHelper.startPage(0, 10000);
        List<SpecimenUrl> lists = specimenMapper.getNoWaterImage();
        PageInfo<SpecimenUrl> pageInfo = new PageInfo<SpecimenUrl>(lists);
        return pageInfo;
    }

    public  void batchUpdateImage(List<String> list){
        specimenMapper.batchUpdateImage(list);
    }



    public  List<Stat> getStatGroupByType(){
        return specimenMapper.getStatGroupByType();
    }

    public Integer getTotal(){
        return specimenMapper.getTotal(null);
    }

    public Integer getYesterdayTotal(){
        String yesterday = TimeUtil.getYesterday();
        return specimenMapper.getTotal(yesterday);
    }

    public Integer getNowTotal(){
        String now = TimeUtil.getNow();
        return specimenMapper.getTotal(now);
    }

    public Integer getImageTotal(){
        return specimenMapper.getImageTotal(null);
    }

    public Integer getYesterdayImageTotal(){
        String yesterday = TimeUtil.getYesterday();
        return specimenMapper.getImageTotal(yesterday);
    }

    public Integer getNowImageTotal(){
        String now = TimeUtil.getNow();
        return specimenMapper.getImageTotal(now);
    }

    public List<Stat> getTotalGroupByDate(String startTime,String endTime){
        return specimenMapper.getTotalGroupByDate(startTime,endTime);
    }

    public Stat getFamilyTotal(){
        Stat st = new Stat();
        st.setName("科");
        st.setValue(Double.valueOf(specimenMapper.getFamilyTotal()));
        return st;
    }

    public Stat getGenusTotal(){
        Stat st = new Stat();
        st.setName("属");
        st.setValue(Double.valueOf(specimenMapper.getGenusTotal()));
        return st;
    }

    public Stat getSpeciesTotal(){
        Stat st = new Stat();
        st.setName("种");
        st.setValue(Double.valueOf(specimenMapper.getSpeciesTotal()));
        return st;
    }

    public Integer getImageTotalByType(Integer isVideo,Integer type){
        return specimenMapper.getImageTotalByType(isVideo,type);
    }
}
